/**
 * Class $$.util.Thread
 * @type class
 * @author TCL
 * @version 1
 * @since 1
 */

/**
 * @param int defaultDelay
 * @param object|arguments tasks
 * @return void
 */
$$.util.Thread = function(defaultDelay, tasks){
	var me = this
		,buffer = {}
		,tIds = {};
	
	defaultDelay = 0 <= defaultDelay? defaultDelay : 1000;
	
	$$.put(me, {
		/**
		 * add a/an tasks to buffer
		 * @param array|arguments tasks
		 * @return $$.util.Thread this
		 */
		add: function(tasks){
			if('object' == typeof tasks) ts = tasks;
			else ts = arguments;
			for(var i = 0; i < ts.length; ++i){
				var t = ts[i];
				t.id = t.id || $$.id();
				buffer[t.id] = t;
			}
			return me;
		}
	
		/**
		 * start all tasks from buffer
		 * @param arguments
		 * @return $$.util.Thread this
		 */
		,start: function(/*args*/){
			if(arguments.length > 0) me.add(arguments);
			for(var i in buffer){
				var t = buffer[i];
				// execute for first time
				t.call.apply(t.scope, t.args || []);
				
				// create & execute the repeat thread
				tIds[i] = t.call.create(t.scope, t.args, null, null, t.delay || defaultDelay)();
			}
			return me;
		}
		
		/**
		 * stop a task by id
		 * @param string id
		 * @return $$.util.Thread
		 */
		,stop: function(id){
			clearInterval(tIds[id]);
			return me;
		}
		
		/**
		 * stop all task
		 * @return $$.util.Thread
		 */
		,stopAll: function(){
			for(var i in tIds) me.stop(i);
			return me;
		}	
	});
	
	if(tasks) me.add(tasks);
};